//
//  HBSetPasswordCtrl.m
//  HuoBao
//
//  Created by 于会海 on 15/11/26.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "HBSetPasswordCtrl.h"
#import "CheckValid.h"
#import "HBRegistParam.h"
#import "HBRegistParser.h"
#import "HBLoginUserInfo.h"
#import "HBLoginManager.h"
#import "HBTabBarViewController.h"
#import "NSString+MKNetworkKitAdditions.h"
#import "HBSetPushAccountManager.h"

@interface HBSetPasswordCtrl ()<UITextFieldDelegate>

@property (strong,nonatomic) UILabel* alertLabel;
@property (weak, nonatomic) IBOutlet UIButton *closeOPBtn;
@property (weak, nonatomic) IBOutlet UITextField *passwordsFiled;
@property (weak, nonatomic) IBOutlet UITextField *invitCodeFiled;
@property (weak, nonatomic) IBOutlet UIButton *confirmBtn;
@property (weak, nonatomic) IBOutlet UIButton *cloesBtn;
@property (nonatomic, strong) UITextRange* previousSelection;
@property (nonatomic, strong) NSString*    previousTextFieldContent;

- (IBAction)confirmAction:(id)sender;
- (IBAction)cleanAction:(UIButton *)sender;
- (IBAction)closeOPBtnACtion:(UIButton *)sender;

@end

@implementation HBSetPasswordCtrl

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}
- (void)doBack{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)buildLayout{
    self.cloesBtn.alpha = 0;
    self.title = @"设置密码";
    self.view.backgroundColor = [LCCommon getColor:@"262626"];
    self.passwordsFiled.delegate = self;
    self.invitCodeFiled.delegate = self;
    self.passwordsFiled.keyboardType = UIKeyboardTypeASCIICapable;
    [self setTextFieldPlaceHolder:self.passwordsFiled];
    [self setTextFieldPlaceHolder:self.invitCodeFiled];
    [self.passwordsFiled addTarget:self action:@selector(passwordsEdit:) forControlEvents:UIControlEventEditingChanged];
    self.confirmBtn.layer.masksToBounds = YES;
    self.confirmBtn.layer.cornerRadius = 4;
    [self creatAlertLabel];
}

- (void)creatAlertLabel{
    self.alertLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.confirmBtn.origin.x, self.confirmBtn.origin.y -40, SCREEN_WIDTH - 60, 30)];
    [self.alertLabel setFont:[UIFont systemFontOfSize:13]];
    [self.alertLabel setTextAlignment:NSTextAlignmentLeft];
    [self.alertLabel setTextColor:[LCCommon getColor:@"D4CB0B"]];
    [self.alertLabel setHidden:YES];
    [self.view addSubview:self.alertLabel];
}

#pragma mark -TextField Delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    CGRect frame = textField.frame;
    int offset = frame.origin.y + 10 - (self.view.frame.size.height - 216.0 -60 -64);
    [UIView animateWithDuration:0.3 animations:^{
        if(offset > 0){
            self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
        }
    }];
    if (self.passwordsFiled == textField) {
        [UIView animateWithDuration:0.4 animations:^{
          self.view.frame = CGRectMake(0.0f, 64, self.view.frame.size.width, self.view.frame.size.height);
        }];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    self.previousTextFieldContent = textField.text;
    self.previousSelection = textField.selectedTextRange;
    
    self.alertLabel.text = @"";
    if ([string isEqualToString:@"\n"]){
        return YES;
    }
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (self.passwordsFiled == textField){
        if ([toBeString length] > 5){
            if ([CheckValid isBothNumberAndCharString:toBeString limitedLengthMoreThan:6 lessThan:12]) {
                [self setBtnDoPress];
            }else{
                [self.alertLabel setText:@"密码为6到12位的数字和字母组合"];
                [self.alertLabel setHidden:NO];
                [self setBtnNoPress];
            }
            if ([toBeString length] > 11) {
                textField.text = [toBeString substringToIndex:12];
                [textField resignFirstResponder];
                return NO;
            }
        }else{
            self.confirmBtn.enabled = NO;
        }
    }
    return YES;
}

- (void)passwordsEdit:(UITextField*)textField{
    if (self.passwordsFiled == textField) {
        //第几次输入
        NSUInteger targetCursorPosition =[textField offsetFromPosition:textField.beginningOfDocument toPosition:textField.selectedTextRange.start];
        
        NSString* nStr = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        NSString* preTxt = [self.previousTextFieldContent stringByReplacingOccurrencesOfString:@" " withString:@""];
        
        char editFlag = 0;
        if (nStr.length <= preTxt.length) {
            editFlag = 0;
            //            LLog(@"删除第%li个",(long)targetCursorPosition+1);
            if (targetCursorPosition == 0) {
                [UIView animateWithDuration:0.25 animations:^{
                    self.cloesBtn.alpha = 0;
                }];
                
            }
        }else {
            editFlag = 1;
            //            LLog(@"增加第%li个",(long)targetCursorPosition+1);
            if (targetCursorPosition == 1) {
                [UIView animateWithDuration:0.25 animations:^{
                    self.cloesBtn.alpha = 1;
                }];
                
            }
        }
    }


}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.passwordsFiled resignFirstResponder];
    [self.invitCodeFiled resignFirstResponder];
//    self.view.frame =CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height);
}
- (void)setTextFieldPlaceHolder:(UITextField*)textField  {
    textField.font = [UIFont systemFontOfSize:15];
    textField.textColor = [LCCommon getColor:@"ffffff"];
    [textField setValue:[LCCommon getColor:@"5e5e5f"] forKeyPath:@"_placeholderLabel.textColor"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)confirmAction:(id)sender {
    
    if (![CheckValid isBothNumberAndCharString:self.passwordsFiled.text limitedLengthMoreThan:6 lessThan:12]){
        self.alertLabel.hidden = NO;
        self.alertLabel.text = @"密码为6到12位的数字和字母组合";
    }
    else{
        [self requestToSubmit];
    }
}
- (void)requestToSubmit{
    HBRegistParam* param = [[HBRegistParam alloc] init];
    param.mobile = self.phoneNum;
    param.password = self.passwordsFiled.text.md5;
    param.mobileCode = self.mobileCode;
    param.inviteCode = self.invitCodeFiled.text;
    param.os = DefaultSystemVersion;
    param.gid = [self getGID];
    param.osVersion = DefaultAppVersion;
    param.channel = @"";
    param.factory = @"";
    param.model = @"";
    param.appVersion = @"";
    param.resolution = @"";
    HBRegistParser* parser = [[HBRegistParser alloc] init];
    
    [CustomLoadingView showHudToView:self.view];
    [NetCenter postDataFromURL:Method_regist params:param parser:parser result:^(ParserResult *myResult) {
        [CustomLoadingView hideHudForView:self.view];
        if (myResult.code == 0) {
            HBLoginUserInfo *info = (HBLoginUserInfo *)myResult.result;
            [HBLoginManager cacheCurrentUserToUserDefault:info];
            [HBSetPushAccountManager requestToSetPushAccountWithResult:^(BOOL isSuccess, NSString *msg, NSError *error) {
                
            }];
            
            HBTabBarViewController* tabBar = [[HBTabBarViewController alloc] init];
            [UIApplication sharedApplication].keyWindow.rootViewController = tabBar;
        }else{
            DISSMISS_ERR(myResult.message);
//            self.alertLabel.text = myResult.message;
        }
    } failure:^(NSError *error) {
        [CustomLoadingView hideHudForView:self.view];
        DISSMISS_ERR(error.description);
    }];

}

- (IBAction)cleanAction:(UIButton *)sender {
    self.passwordsFiled.text = @"";
    [UIView animateWithDuration:0.25 animations:^{
        self.cloesBtn.alpha = 0;
    }];
    
}

- (IBAction)closeOPBtnACtion:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected == YES) {
        self.passwordsFiled.secureTextEntry = YES;
    }else{
        self.passwordsFiled.secureTextEntry = NO;
    }
}

- (void)setBtnNoPress{
    [self.confirmBtn setBackgroundColor:[LCCommon getColor:Btn_Disable] forState:UIControlStateNormal];
    self.confirmBtn.enabled = NO;
}
- (void)setBtnDoPress{
    [self.confirmBtn setBackgroundColor:[LCCommon getColor:Btn_Normal] forState:UIControlStateNormal];
    self.confirmBtn.enabled = YES;
}

- (NSString*)getGID{
    NSUUID *identifierForVendor = [[UIDevice currentDevice] identifierForVendor];
    NSString *deviceId = [identifierForVendor UUIDString];
    return deviceId;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.navigationController.navigationBarHidden = NO;
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    self.navigationController.navigationBarHidden = YES;
}
@end
